package com.css.ids.server.common.filter;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.css.util.StringHelper;

public class IPHelper {
	
	public static boolean isMatch(List<String> ipPatterns,String ip){
		if(ipPatterns==null){return false;}
		if(StringHelper.isEmpty(ip)){return false;}
		if("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)){
			return true;
		}
		for(String ipPattern : ipPatterns){
			if(ip.matches(ipPattern)){
				return true;
			}
		}
		return false;
	}

	public static String getIpAddr(HttpServletRequest request) {
		String ipAddress = null;
		// ipAddress = this.getRequest().getRemoteAddr();
		ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0
				|| "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
			//if (ipAddress.equals("127.0.0.1")) {
				InetAddress inet = null;
				try {
					// 根据网卡取本机配置的IP
					//inet = InetAddress.getLocalHost();
					inet = InetAddress.getByName(ipAddress);
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ipAddress = inet.getHostAddress();
			//}

		}
		return ipAddress;
	}
	
	
	public static void main(String[] args) {
		InetAddress inet = null;
		try {
			//inet = InetAddress.getLocalHost();
			inet = InetAddress.getByName("127.0.0.1");
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		String ipAddress = inet.getHostAddress();
		System.out.println(ipAddress);
		
		String a = "a123345";
		System.out.println(a.matches("[0-9]*"));
	}
}
